package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.Barrels;

public class BarrelsPresenter extends AbstractPresenter<Barrels> {
	final String SINGLEITEM = "barrels";
	final String MULTIITEM = "barrelss";
	
	public ArrayList<Barrels> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public Barrels tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public Barrels createItemFromJSONObject(JSONObject jsonObject){
		Barrels item = new Barrels();
		try{
			item.setBarrelDesc(jsonObject.getString("barDisc"));
			item.setBarrelID(jsonObject.getInt("barID"));
			item.setBarrelNotes(jsonObject.getString("barNotes"));
			item.setBarrelVol(jsonObject.getDouble("barVol"));
			item.setCurrentVol(jsonObject.getDouble("currentVol"));
			item.setDateFilled(timeFormat.parse(jsonObject.getString("dateFilled")));
			item.setPastBatches(jsonObject.getString("pastBatches"));
			
			if(!jsonObject.isNull("currentBatch")){
				BrewViewPresenter presenter = new BrewViewPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("currentBatch");
				item.setCurrentBatch(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setCurrentBatch(null);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(Barrels item){
		try{
			JSONObject json = new JSONObject();
			json.put("barDisc", item.getBarrelDesc());
			json.put("barID", item.getBarrelID());
			json.put("barNotes", item.getBarrelNotes());
			json.put("barVol", item.getBarrelVol());
			json.put("currentVol", item.getCurrentVol());
			json.put("dateFilled", getDate(item.getDateFilled()));
			json.put("pastBatches", item.getPastBatches());

			if(item.getCurrentBatch()!=null){
				BrewViewPresenter presenter = new BrewViewPresenter();
				json.put("currentBatch", presenter.createJSON(item.getCurrentBatch()));
			} else {
				json.put("currentBatch", JSONObject.NULL);
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public Barrels getEmptyEntity(){
		Barrels entity = new Barrels();
		return entity;
	}
}
